<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
	defined ('IN_AGORA') or die;
	
	class AggregatorModel extends Model
	{
		function __construct()
		{
			parent::__construct('feeds');
		}
		
		function _cleanup( $str, $enc_from, $enc_to ) {
			//$str = iconv( $enc_from, $enc_to, $str );
			$str = str_replace(
				array( "</p>\n\n", "</p>\n", "<br>\n", "<br>", "<br />\n", "<br />" ),
				array( "\n\n", "\n\n", "\n", "\n", "\n", "\n" ),
				$str
			);
			$str = preg_replace( '#<img.*?src="([^"]+)"[^>]*>#i', "[img]$1[/img]", $str );
			$str = preg_replace( '#<a.*?href="([^"]+)"[^>]*>([^<]+?)</a>#ie', "'[url=\\1]'.strtr('\\2',\"\n\r\",'  ').'[/url]'", $str );
			$str = html_entity_decode( $str, ENT_QUOTES, $enc_to );
			$str = strip_tags( $str );
			return $str;
		}
		
		function runJob()
		{
			jimport('simplepie.simplepie');
//			include(AGORA_PATH . 'include' . DS . 'simplepie.inc');
			$feed = new SimplePie();
			//$feed->set_cache_location( AGORA_PATH.'cache'.DS );
			$feed->set_cache_location( JPATH_ROOT . DS . 'cache' . DS . 'com_agora' . DS);
			
			$this->db->setQuery("SELECT id, url, max, closed, author, forum_id FROM {$this->table}");
			$data = $this->db->loadAssocList();
			if ($data)
			foreach ($data as $row) {
				$feed_id = $row['id'];
				$url = $row['url'];
				$max = $row['max'];
				$f_author = $row['author'];
				$max_time = time();
				$closed = intval( $row['closed'] );
				$fid = intval($row['forum_id']);
				
				$this->setQuery("SELECT 1 FROM ##__forums WHERE id = $fid");
				if( $this->db->loadResult() !== "1" ) continue;
				$feed->set_feed_url( $url );
				$feed->set_output_encoding('utf-8');
				$feed->init();
				$feed->handle_content_type();
				if( ! $feed->data ) continue;
				$title = $feed->get_title();
				$cont = 0;	
				for( $i = 0; ( $max <= 0 || $i < $max ) && $item = $feed->get_item($i); $i++ ) {
					$time = $item->get_date('Y-m-d H:i:s');
					$time = $time ? strtotime( $time ) : time();
					$author = $item->get_author(0);
					if( $author ) {
						$email = $this->db->Quote($author->get_email());
						if( empty( $username ) ) $username = $email;
					} else {
						$email = '';
					}
					$username = $f_author;
					
					$username = iconv( $feed->get_encoding(), 'UTF-8', $username );
					$username = $this->db->Quote( $username );
					$email = $this->db->Quote($email);
					$subject = '['.$title.'] '.( $item->get_title() ? $item->get_title() : basename( $item->get_permalink() ) );
					$subject = $this->db->Quote( $this->_cleanup( $subject, $feed->get_encoding(), 'UTF-8' ));
					$message = $item->get_description()."\n\n[url]".$item->get_permalink()."[/url]";
					$message = $this->db->Quote( $this->_cleanup( $message, $feed->get_encoding(), 'UTF-8' ) );
					// skip duplicates
					$this->setQuery("SELECT 1 FROM ##__topics WHERE poster = $username AND subject = $subject AND forum_id = $fid");
					if( $this->db->loadResult() === '1' ) continue;
					// Create the topic
					$this->setQuery("INSERT INTO ##__topics (poster, subject, posted, last_post, last_poster, closed, forum_id) VALUES($username, $subject, $time, $time, $username, $closed, $fid)");
					$this->db->query();
					$new_tid = $this->db->insertid();
					// Insert the new post
					$this->setQuery("INSERT INTO ##__posts (poster, poster_ip, poster_email, message, hide_smilies, posted, topic_id) VALUES($username, '', $email, $message, '0', $time, $new_tid)");
					$this->db->query();
					$new_pid = $this->db->insertid();
					// Update the topic with last_post_id
					$this->setQuery("UPDATE ##__topics SET last_post_id=$new_pid WHERE id=$new_tid");
					$this->db->query();
					$max_time = max( $max_time, $time );
					$cont++;
				}
				
				if( $cont > 0 ) {
					$this->setQuery("UPDATE ##__feeds SET last_post=$max_time, num_posts = num_posts + $cont WHERE id=$feed_id");
					$this->db->query();
					$this->setQuery("SELECT last_post_id FROM ##__topics WHERE poster = $username AND forum_id = $fid ORDER BY posted DESC LIMIT 1");
					$last_post_id = (int)$this->db->loadResult();
					$this->setQuery("UPDATE ##__forums SET last_post=$max_time, num_topics = num_topics + $cont, last_poster = $username, last_post_id = $last_post_id WHERE id=$fid");
					$this->db->Query();
				}
			}
		}
		
		function addFeed($url, $forum_id, $max, $closed, $author)
		{
			$q_url = $this->db->Quote($url);
			$author = $this->db->Quote($author);
			$max = intval($max);
			$forum_id = intval(trim($forum_id));
			$closed = intval($closed);
			
			$this->setQuery("INSERT INTO ##__feeds".
						" (url, forum_id, max, closed, author)".
						" VALUES ($q_url, $forum_id, $max, $closed, $author) ");
			$this->db->query();
		}
		
		function loadFeeds($per_page,$page)
		{
			$limit = $this->getLimit($per_page,$page);
			$this->setQuery('SELECT feeds.*, forums.forum_name FROM ##__feeds AS feeds LEFT JOIN ##__forums AS forums ON feeds.forum_id = forums.id ORDER BY url '.$limit);
			return $this->db->loadAssocList();
		}

		function feedExists($url)
		{
			$this->setQuery('SELECT COUNT(*) FROM ##__feeds WHERE url = '.$this->db->Quote(trim($url)));
			return $this->db->loadResult() > 0;
		}

		function delete($url)
		{
			$this->setQuery('DELETE FROM ##__feeds WHERE url = '. $this->db->Quote(trim($url)));
			$this->db->query();
		}
	}
?>